package com.briup.web.controller.part4;

import com.briup.bean.Student;
import com.briup.bean.Teacher;
import com.briup.exception.TeacherException;
import com.briup.service.ITeacherService;
import com.briup.service.TeacherServiceImpl;
import com.briup.util.Result;
import com.briup.util.ResultCode;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import java.io.IOException;
import java.sql.SQLException;

/**
 * 教师信息模块
 */
@Controller
@RequestMapping("/teacher")
public class TeacherController {
    @Autowired
    private ITeacherService service;


    @RequestMapping("/findTeacherById")
    @ResponseBody
    public Result findTeacherById(Integer id){
        Teacher t = null;
        try{
            // System.out.println(1/0); 语法抛出异常、
            //调用service代码时 service方法抛出异常
            t = service.findTeacherById(id);
        }catch (Exception e){
            e.printStackTrace();
            if(e instanceof TeacherException){
                return new Result(10002,e.getMessage());
            }
            if(e instanceof SQLException){
                return new Result(10002,"数据库存在错误");
            }
            return new Result(10002,"程序内部错误");
        }
        return  Result.success(t);
    }
    @RequestMapping("/addTeacher")
    public Result addTeacher(Teacher t) throws Exception{
        //调用service层代码
        //处理异常的逻辑代码try catch
       // System.out.println(1/0);
        System.out.println(t);
        if(t.getId() == 0){
            throw new TeacherException("工号不为0错误");
        }
        if(t.getId() == 1){
            System.out.println(1/0);
        }
        return  null;
    }
    //当前类中方法抛出任意异常，自动调用该方法处理异常
    //@ExceptionHandler(Exception.class)
    //@ExceptionHandler(IOException.class)
    //@ExceptionHandler(Exception.class)
    public String handleException(Exception e, Model m){
        System.out.println("处理TeacherController中异常:"+e.getMessage());
        String msg= "程序内部错误";
        if (e instanceof TeacherException){
            msg = e.getMessage();
        }
        m.addAttribute("msg",msg);
        return "error";//error.jsp
    }
    //@ExceptionHandler(TeacherException.class)
    //@ResponseBody
    public Result handleException(Exception e){
        return new Result(10001,e.getMessage());
    }
}
